package com.xbongbong.saas.help.workorder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.feign.WorkOrderV2ImportFeignClient;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.FormatExportDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.help.ImportHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 李翔
 * @date 2022/11/21
 * @description
 */
@Component
public class WorkOrderV2ImportHelp {

    @Resource
    private ImportHelper importHelper;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderV2ImportFeignClient workOrderV2ImportFeignClient;

    public FormDataAddDTO formatExcelValue4ServiceProject(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        // data 数据
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        // 遍历数据
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            String attrName = fieldAttr.getAttrName();
            Integer fieldType = fieldAttr.getFieldType();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                continue;
            }
            if (ImportHelper.commonHandleFieldType.contains(fieldType)) {
                importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
            } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                formDataAddDTO.setSerialNo(cellValue.toString());
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
            } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
            } else {
                dataJson.put(attr, cellValue);
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    /**
     * 格式化导出值
     *
     * @param paasFormDataESList
     * @param formDataListDTO
     */
    public void formatWorkOrderV2ExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO) {
        //查工单关联数据(产品、当前节点、来源工单池)
        FormatExportDTO formatExportDTO = new FormatExportDTO(paasFormDataESList.stream().map(PaasFormDataEntity::getId).collect(Collectors.toList()), formDataListDTO.getCorpid());
        String exportFormatStr = workOrderV2ImportFeignClient.exportFormat(formatExportDTO);
        JSONObject resultJson = (JSONObject) (JSONObject.parseObject(exportFormatStr, XbbResponse.class).getResult());
        Object productObj = resultJson.get("array_1");
        Map<Long, JSONArray> productMap = Objects.nonNull(productObj) ? (Map<Long, JSONArray>) productObj : null;
        Object phaseObj = resultJson.get("text_5");
        Map<Long, String> phaseMap = Objects.nonNull(phaseObj) ? (Map<Long, String>) phaseObj : null;
        Object poolObj = resultJson.get("text_7");
        Map<Long, String> poolMap = Objects.nonNull(poolObj) ? (Map<Long, String>) poolObj : null;
        paasFormDataESList.forEach(entity -> {
            int id = entity.getId().intValue();
            //工单产品(JsonObject默认Integer,Long接不到)
            entity.getData().put("array_1", Objects.nonNull(productMap) ? productMap.get(id) : null);
            //当前阶段
            entity.getData().put("text_5", Objects.nonNull(phaseMap) ? phaseMap.get(id) : null);
            //来源工单池
            entity.getData().put("text_7", Objects.nonNull(poolMap) ? poolMap.get(id) : null);
            //渲染一下处理时长
            if (Objects.nonNull(entity.getData().get("num_7"))){
                Integer processingTime=entity.getData().getInteger("num_7");
                String processingTimeStr= DateUtil.secondToTimeTip(processingTime);
                entity.getData().put("num_7", processingTimeStr);
            }
        });
    }

    /**
     * 格式化导入值
     *
     * @param importFormDataDTO
     * @param titlePojoList
     * @param rowGroupPojo
     * @param fieldAttrList
     * @return
     */
    public FormDataAddDTO formatExcelValue4WorkOrderV2(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        List<CellValuePojo> cellValueList = rowValueList.get(0);

        FieldAttrEntityForImport linkCustomerAttr = null;
        for (FieldAttrEntityForImport fieldAttrEntityForImport : fieldAttrList) {
            if (Objects.equals(fieldAttrEntityForImport.getAttr(), ContractEnum.LINK_CUSTOMER.getAttr())) {
                linkCustomerAttr = fieldAttrEntityForImport;
                break;
            }
        }
        Long linkCustomerId = 0L;
        if (Objects.nonNull(linkCustomerAttr)) {
            linkCustomerId = importHelper.formatLinkCustomer2CustomerId(titlePojoList, dataJson, rowValueList, linkCustomerAttr);
        }

        String corpid = importFormDataDTO.getCorpid();
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(attr, "array_1")) {
                //关联产品格式化
                importHelper.formatCommonProduct(titlePojoList, dataJson, rowValueList, fieldAttr, XbbRefTypeEnum.WORK_ORDER_V2.getCode(), corpid);
            } else if (Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())) {
                //关联客户上面单独处理过了
            } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                //子表单(地址)
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else if (Objects.equals(attr, "text_81")) {
                    importHelper.formatRelyBusiness(linkCustomerId, dataJson, fieldAttr, cellValue, "text_2");
                } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                    formDataAddDTO.setSerialNo(cellValue.toString());
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                    importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                } else {
                    dataJson.put(attr, cellValue);
                }

            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    /**
     * 工单2.0导入
     *
     * @param formDataAddDTO
     * @return
     */
    public FormDataAddVO addAndImport(FormDataAddDTO formDataAddDTO) {
        String responseStr = workOrderV2ImportFeignClient.add(formDataAddDTO);
        XbbResponse xbbResponse = JSON.parseObject(responseStr, XbbResponse.class);
        return JSON.parseObject(JSON.toJSONString(xbbResponse.getResult()), FormDataAddVO.class);
    }

    /**
     * 工单2.0 更新 、导入
     *
     * @param formDataUpdateDTO
     * @return
     */
    public FormDataUpdateDTO updateAndImport(FormDataUpdateDTO formDataUpdateDTO) {
        String responseStr = workOrderV2ImportFeignClient.update(formDataUpdateDTO);
        XbbResponse xbbResponse = JSON.parseObject(responseStr, XbbResponse.class);
        return JSON.parseObject(JSON.toJSONString(xbbResponse.getResult()), FormDataUpdateDTO.class);
    }
}
